/*
 * @Author: zulezhe
 * @Date: 2021-11-18 10:57:32
 * @LastEditors: zulezhe
 * @LastEditTime: 2022-03-28 15:32:03
 * @Path: https://gitee.com/zulezhe/
 * @Description:
 */
import { getToken } from "./auth.js";
import axios from 'axios'
/**
 * 格式化时间
 * @param {*} time
 * @param {*} cFormat
 * @returns
 */
export function parseTime(time, cFormat) {
	if (arguments.length === 0) {
		return null;
	}
	// const format = cFormat || "{y}-{m}-{d}";
	const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
	let date;
	if (typeof time === "object") {
		date = time;
	} else {
		if (("" + time).length === 10) time = parseInt(time) * 1000;
		date = new Date(time);
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay(),
	};
	const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key];
		if (key === "a")
			return ["一", "二", "三", "四", "五", "六", "日"][value - 1];
		if (result.length > 0 && value < 10) {
			value = "0" + value;
		}
		return value || 0;
	});
	return timeStr;
}
// 日期格式化
export function parseTimeDate(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm),'');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		// h: date.getHours(),
		// i: date.getMinutes(),
		// s: date.getSeconds(),
		// a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}
/**
 *
 * @param {*} time
 * @param {*} option
 * @returns
 */
export function formatTime(time, option) {
	time = +time * 1000;
	const d = new Date(time);
	const now = Date.now();

	const diff = (now - d) / 1000;

	if (diff < 30) {
		return "刚刚";
	} else if (diff < 3600) {
		// less 1 hour
		return Math.ceil(diff / 60) + "分钟前";
	} else if (diff < 3600 * 24) {
		return Math.ceil(diff / 3600) + "小时前";
	} else if (diff < 3600 * 24 * 2) {
		return "1天前";
	}
	if (option) {
		return parseTime(time, option);
	} else {
		return (
			d.getMonth() +
			1 +
			"月" +
			d.getDate() +
			"日" +
			d.getHours() +
			"时" +
			d.getMinutes() +
			"分"
		);
	}
}

/**
 * 对Date的扩展，将 Date 转化为指定格式的String
 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符
 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 * @example:
 * (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 * (new Date()).Format("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
 * (new Date()).Format("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
 * (new Date()).Format("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
 * (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */

export function timeFormat(time, fmt = "yyyy-MM-dd HH:mm:ss") {
	time = new Date(time);
	const o = {
		"M+": time.getMonth() + 1, // 月份
		"d+": time.getDate(), // 日
		"h+": time.getHours() % 12 === 0 ? 12 : time.getHours() % 12, // 小时
		"H+": time.getHours(), // 小时
		"m+": time.getMinutes(), // 分
		"s+": time.getSeconds(), // 秒
		"q+": Math.floor((time.getMonth() + 3) / 3), // 季度
		S: time.getMilliseconds(), // 毫秒
	};
	const week = {
		0: "日",
		1: "一",
		2: "二",
		3: "三",
		4: "四",
		5: "五",
		6: "六",
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(
			RegExp.$1,
			(time.getFullYear() + "").substr(4 - RegExp.$1.length)
		);
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt.replace(
			RegExp.$1,
			(RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? "星期" : "周") : "") +
			week[time.getDay() + ""]
		);
	}
	for (const k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(
				RegExp.$1,
				RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
			);
		}
	}
	return fmt;
}
/**
 * 时间分割
 * @param {*} startDate 开始时间
 * @param {*} endDate  结束时间
 * @param {*} amount   分割次数
 * @return {Array} temp 分割后的时间
 */
export function timeRange(startDate, endDate, amount) {
	const startTime = new Date(startDate);
	const endTime = new Date(endDate);
	const gap = (endTime - startTime) / amount;
	const temp = [];
	for (let i = 0; i < amount; i++) {
		startTime.setMilliseconds(startTime.getMilliseconds() + gap);
		temp[i] = timeFormat(new Date(startTime.getTime()));
	}
	return temp;
}
  // 下载方法
 export function downloadFunc(param){
    const {
      method = 'get', url = '', target = '', data = {}
    } = param
    param.type = param.type||'download';
    let str = ''
    for (const key in data) {
      str += `<input name='${key}' value='${data[key]}' type='hidden' />`
    }
    const form = document.createElement('form');
    form.action = param.type=='download'?process.env.VUE_APP_API_PREFIX + url:url;
    form.method = method;
    form.target = target;
    form.style.display = 'none'
    document.body.appendChild(form)
    form.innerHTML = str
    form.submit()
    document.body.removeChild(form)
}
/**
 * 导出excel文件
 * 张志瑞
 * @param {*} options
 * @returns
 */
export function postExport(options) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      baseURL: process.env.VUE_APP_API_PREFIX,
      responseType: 'blob', // 表明返回服务器返回的数据类型
      headers: {
        'Authorization': "Bearer " + getToken(),
      },
      ...options
    }).then(response => { // 处理返回的文件流
      console.log(response)
      const blob = new Blob([response.data], { type: 'application/octet-stream;charset=utf-8' })
      console.log(blob)
      let filename = response.headers['content-disposition']
      console.log(filename)
      const index = filename.indexOf('fileName=')
      if (index > -1) {
        filename = filename.substr(index + 9)
        filename = decodeURI(filename)
      } else {
        filename = filename.substr(index + 21)
        filename = decodeURI(filename)
      }
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
      resolve(response.data)
    }, err => {
      reject(err)
    }).catch(function(error) { // 加上catch
      console.log(error)
    })
  })
}
/**
 * 数组去重
 * @param {*}
 * @return {*}
 * @author: zulezhe
 */
export const deduplication = (arr) => [...new Set(arr)];
/**
 * 保留非重复的数据
 * @param {Array} arr 处理的数组
 * @example
 * filterNonUnique([1,2,2,3,4,1,2])
 * [3, 4]
 */
export const filterNonUnique = (arr) =>
	arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
/**
 * 保留重复的数据
 * @param {Array} arr 处理的数组
 * @example
 * saveUnique([1,2,2,3,4,1,2])
 * [1, 2, 2, 1, 2]
 */
export const saveUnique = (arr) =>
	arr.filter((i) => arr.indexOf(i) !== arr.lastIndexOf(i));
/**
 * @param {*} data 数据
 * @param {*} key  参考值
 * @return {*}
 * @author: zulezhe
 * @Path: https://gitee.com/zulezhe/
 */
export function delEqualForArrObj(data, key) {
	let obj = {};
	return data.reduce((cur, next) => {
		obj[next[key]] ? "" : (obj[next[key]] = true && cur.push(next));
		return cur;
	}, []);
}
/**
 * 查找数组中相等的项
 * @param {*} arr
 * @param {*} key
 * @param {*} val
 * @return {*}
 * @author: zulezhe
 */
export function findEqual(arr, key, val) {
	for (let i = 0; i < arr.length; i++) {
		const ele = arr[i];
		if (ele[key] === val) {
			return ele;
		}
	}
}
/**
 * 根据val查找数组对象中相同val的项,返回Object,根据id查找tree数据中相等数据label
 * @param {*}
 * @return {*}
 * @author: zulezhe
 */
export function findKeyValue(arr, val) {
	let obj;

	function test(arr) {
		arr.forEach((ele) =>
			ele.id === val ? (obj = ele) : ele.children ? test(ele.children) : ""
		);
	}
	test(arr);
	return obj;
}
/**
 *  @description: 对象转 url
 *  @param {Object} obj 对象形式
 *  @return {String} 字符串 类似 news_id=144&scorce=seo
 *  @author: wangchaoxu
 *  @remark 有bug,参数有时间的话,会被格式化
 */
export function jsonToUrl(obj) {
	obj = JSON.stringify(obj);
	return obj
		.replace(/:/g, "=")
		.replace(/"/g, "")
		.replace(/,/g, "&")
		.match(/\{([^)]*)\}/)[1];
}

/**
 * url形式字符串 转对象
 * @param {string} url
 * @returns {object }
 * @example
 *  urlToObj("username=a23131&password=052a1a3c0142ad636571f88ea2506eac")
 *  //{ username: 'a23131', password: '052a1a3c0142ad636571f88ea2506eac' }
 */
export function urlToObj(url) {
	return JSON.parse(
		'{"' + url.replace(/&/g, '","').replace(/=/g, '":"') + '"}',
		function(key, value) {
			return key === "" ? value : decodeURIComponent(value);
		}
	);
}
/**
 * 去除对象中所有符合条件的对象
 * @param {Object} obj 来源对象
 * @param {Function} fn 函数验证每个字段
 */
export function compactObj(obj, fn) {
	for (const i in obj) {
		if (typeof obj[i] === "object") {
			compactObj(obj[i], fn);
		}
		if (fn(obj[i])) {
			delete obj[i];
		}
	}
}
/**
 * 数组对象求和
 * @param {*}
 * @return {*}
 * @author: zulezhe
 */
export function objSum(arr, ...param) {
	const temp = {};
	arr.forEach(function(item, index) {
		for (const k in item) {
			if (param.includes(k)) {
				if (typeof item[k] === "string") {
					item[k] = item[k] * 1;
				}
				if (temp[k]) {
					temp[k] += item[k];
				} else {
					temp[k] = item[k];
				}
			}
		}
	});
	return temp;
}
/**
 * @description: 从数组中找到最接近的数
 * @param {Number}  val
 * @param {Array}   data
 * @return {Number} 最接近当前值的结果
 * @author: wangchaoxu
 */
export function findNearByArr(val, data) {
	if (data.includes) return val;
	data.push(val);
	const newArr = data.sort((a, b) => a - b);
	const pre = newArr[newArr.indexOf(val) - 1];
	const next = newArr[newArr.indexOf(val) + 1];
	return val - pre > next - val || val - pre === next - val ? next : pre;
}
/**
 * @description: 避免数组漏删for循环
 * @param {Array} arr 数组
 * @param {Function} callback 回调函数
 * @author: wangchaoxu
 */
export function for2(arr, callback) {
	for (let i = arr.length; i > 0;) {
		i--;
		const item = arr[i];
		if (typeof callback === "function") {
			callback(item);
		}
	}
}
/**
 * 上传验证
 * @param {*}
 * @return {*}
 * @author: zulezhe
 */
export function lastSubstring(str, split) {
	if (
		str === undefined ||
		str === null ||
		split === undefined ||
		split === null
	) {
		return "";
	}
	return str.substring(str.lastIndexOf(split) + 1);
}
/*
 *
 * @param {、} files
 * @param {*} fileType
 * @param {*} fileSize
 * @returns
 */
export function checkFile(files, fileType, fileSize) {
	let flag = true;
	let tip = "";
	files.forEach((item) => {
		// 文件过大
		if (item.size > fileSize * 1024 * 1024) {
			flag = false;
			tip = " 文件超过" + fileSize + "M";
		}
		// 文件类型不属于可上传的类型
		if (!fileType.includes(lastSubstring(item.name, "."))) {
			flag = false;
			tip = " 文件类型不可上传";
		}
	});
	return flag;
}
/**
 * html反转义
 * @param {*} str
 * @return {*}
 * @author: zulezhe
 */
export function escape2Html(str) {
	var arrEntities = {
		lt: "<",
		gt: ">",
		nbsp: " ",
		amp: "&",
		quot: '"',
	};
	return str.replace(/&(lt|gt|nbsp|amp|quot);/gi, function(all, t) {
		return arrEntities[t];
	});
}
/**
 * 数字转千分位
 * @param {*} num
 */
export function numberFormat(num) {
	return ` ${numberParse(num)}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
/**
 * 千分位转普通数字
 * @param {*} num
 */
export function numberParse(num) {
	return num && num.toString().replace(/\$\s?|(,*)/g, "");
}
/**
 * 数字转成 k,w之类结尾的数
 * @param {*} num
 */
export function formatNumber(num) {
	if (num < 1e3) {
		return num;
	} else if (num >= 1e3 && num < 1e4) {
		return (num / 1e3).toFixed(1) + "k";
	} else if (num >= 1e4 && num < 1e6) {
		return (num / 1e4).toFixed(1) + "w";
	} else {
		return (num / 1e6).toFixed(1) + "m";
	}
}

/**
 * 四舍五入保留2位小数（若第二位小数为0，则保留一位小数）
 */
export function keepTwoDecimal(num) {
	var result = parseFloat(num);
	if (isNaN(result)) {
		return false;
	}
	result = Math.round(num * 100) / 100;
	return result;
}
/**
 * 四舍五入保留2位小数（不够位数，则用0替补）
 * @param {*} num
 * @returns
 */
export function keepTwoDecimalFull(num) {
	var result = parseFloat(num);
	if (isNaN(result)) {
		return false;
	}
	result = Math.round(num * 100) / 100;
	var s_x = result.toString();
	var pos_decimal = s_x.indexOf(".");
	if (pos_decimal < 0) {
		pos_decimal = s_x.length;
		s_x += ".";
	}
	while (s_x.length <= pos_decimal + 2) {
		s_x += "0";
	}
	return s_x;
}
/**
 * vite 替换require加载图片
 * @param {*} path 图片储存路径
 * @returns
 */
export function loaderImg(path) {
	// return new URL(path, import.meta.url).href
}

/**
 * 深克隆
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
	if (!source && typeof source !== "object") {
		throw new Error("error arguments", "deepClone");
	}
	const targetObj = source.constructor === Array ? [] : {};
	Object.keys(source).forEach((keys) => {
		if (source[keys] && typeof source[keys] === "object") {
			targetObj[keys] = deepClone(source[keys]);
		} else {
			targetObj[keys] = source[keys];
		}
	});
	return targetObj;
}

/**
 * 首字母大小
 * @param {*} str
 * @returns
 */
export function titleCase(str) {
	return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

/**
 * 下划转驼峰
 * @param {*} str
 * @returns
 */
export function camelCase(str) {
	return str.replace(/_[a-z]/g, (str1) => str1.substr(-1).toUpperCase());
}

export function isNumberStr(str) {
	return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
}
/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
	let timeout, args, context, timestamp, result;

	const later = function() {
		// 据上一次触发时间间隔
		const last = +new Date() - timestamp;

		// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
		if (last < wait && last > 0) {
			timeout = setTimeout(later, wait - last);
		} else {
			timeout = null;
			// 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
			if (!immediate) {
				result = func.apply(context, args);
				if (!timeout) context = args = null;
			}
		}
	};

	return function(...args) {
		context = this;
		timestamp = +new Date();
		const callNow = immediate && !timeout;
		// 如果延时不存在，重新设定延时
		if (!timeout) timeout = setTimeout(later, wait);
		if (callNow) {
			result = func.apply(context, args);
			context = args = null;
		}

		return result;
	};
}
/**
 * 参数转obj
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
	const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
	if (!search) {
		return {};
	}
	const obj = {};
	const searchArr = search.split("&");
	searchArr.forEach((v) => {
		const index = v.indexOf("=");
		if (index !== -1) {
			const name = v.substring(0, index);
			const val = v.substring(index + 1, v.length);
			obj[name] = val;
		}
	});
	return obj;
}
/**
 * 对象转param
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
	if (!json) return "";
	return cleanArray(
		Object.keys(json).map((key) => {
			if (json[key] === undefined) return "";
			return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
		})
	).join("&");
}

/**
 * 表单重置
 * @param {*} refName
 */
export function resetForm(refName) {
	if (this.$refs[refName]) {
		this.$refs[refName].resetFields();
	}
}

/**
 * 添加日期范围
 * @param {*} params
 * @param {*} dateRange
 * @param {*} propName
 * @returns
 */
export function addDateRange(params, dateRange, propName) {
  let search = params;
  search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof (propName) === 'undefined') {
    search.params['beginTime'] = dateRange[0];
    search.params['endTime'] = dateRange[1];
  } else {
    search.params['begin' + propName] = dateRange[0];
    search.params['end' + propName] = dateRange[1];
  }
  console.log('labelSearch',search)
  return search;
}
/**
 * 截取url参数
 */
export function getUrlParam(data) {
	var url = data;
	if (url.includes("?")) {
		var arrUrl = url.split("?");

		var para = arrUrl[1].split("oldFileName=");
		return para[1];
	} else {
		return "";
	}
}

// 回显数据字典
export function selectDictLabel(datas, value) {
	var actions = [];
	Object.keys(datas).some((key) => {
		if (datas[key].value == "" + value) {
			actions.push(datas[key].label);
			return true;
		}
	});
	return actions.join("");
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
	var actions = [];
	var currentSeparator = undefined === separator ? "," : separator;
	var temp = value.split(currentSeparator);
	Object.keys(value.split(currentSeparator)).some((val) => {
		Object.keys(datas).some((key) => {
			if (datas[key].value == "" + temp[val]) {
				actions.push(datas[key].label + currentSeparator);
			}
		});
	});
	return actions.join("").substring(0, actions.join("").length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
	var args = arguments,
		flag = true,
		i = 1;
	str = str.replace(/%s/g, function() {
		var arg = args[i++];
		if (typeof arg === "undefined") {
			flag = false;
			return "";
		}
		return arg;
	});
	return flag ? str : "";
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
	if (!str || str == "undefined" || str == "null") {
		return "";
	}
	return str;
}

// 数据合并
export function mergeRecursive(source, target) {
	for (var p in target) {
		try {
			if (target[p].constructor == Object) {
				source[p] = mergeRecursive(source[p], target[p]);
			} else {
				source[p] = target[p];
			}
		} catch (e) {
			source[p] = target[p];
		}
	}
	return source;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
	let config = {
		id: id || "id",
		parentId: parentId || "parentId",
		childrenList: children || "children",
	};

	var childrenListMap = {};
	var nodeIds = {};
	var tree = [];

	for (let d of data) {
		let parentId = d[config.parentId];
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = [];
		}
		nodeIds[d[config.id]] = d;
		childrenListMap[parentId].push(d);
	}

	for (let d of data) {
		let parentId = d[config.parentId];
		if (nodeIds[parentId] == null) {
			tree.push(d);
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
}
export function formTree(data, id, pid, children) {
	let config = {
		id: id || "id",
		pid: pid || "pid",
		childrenList: children || "children",
	};

	var childrenListMap = {};
	var nodeIds = {};
	var tree = [];

	for (let d of data) {
		let pid = d[config.pid];
		if (childrenListMap[pid] == null) {
			childrenListMap[pid] = [];
		}
		nodeIds[d[config.id]] = d;
		childrenListMap[pid].push(d);
	}

	for (let d of data) {
		let pid = d[config.pid];
		if (nodeIds[pid] == null) {
			tree.push(d);
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
}
// 返回项目路径
export function getNormalPath(p) {
	if (p.length === 0 || !p || p == "undefined") {
		return p;
	}
	let res = p.replace("//", "/");
	if (res[res.length - 1] === "/") {
		return res.slice(0, res.length - 1);
	}
	return res;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
	let result = "";
	for (const propName of Object.keys(params)) {
		const value = params[propName];
		var part = encodeURIComponent(propName) + "=";
		if (value !== null && typeof value !== "undefined") {
			if (typeof value === "object") {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && typeof value[key] !== "undefined") {
						let params = propName + "[" + key + "]";
						var subPart = encodeURIComponent(params) + "=";
						result += subPart + encodeURIComponent(value[key]) + "&";
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&";
			}
		}
	}
	return result;
}

// 验证是否为blob格式
export async function blobValidate(data) {
	try {
		const text = await data.text();
		JSON.parse(text);
		return false;
	} catch (error) {
		return true;
	}
}
/** 数组扁平化处理
 * @param {Array} arr 需要扁平化的对象数组，如 [{},{ children: [{}] }]
 */
export function flatArray(arr) {
	const flatArr = []
	arr.forEach(item => {
		flatArr.push({
			...item
		})
		if (item.children && item.children.length !== 0) {
			flatArr.push(
				...flatArray(item.children)
			)
		}
	})
	return flatArr
}

